<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\Addons;
use app\madmin\model\AddonsVersion;
use app\madmin\model\Article as admin;
use app\madmin\model\UpdateRecord;
use app\utils\Common;
use app\utils\RedisUtil;
use app\utils\TrimData;
use \GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use think\Cache;
use think\Exception;

use think\facade\Config;
use think\facade\Db;
use think\facade\Filesystem;

class AuthenticationService
{



    public function __construct()
    {
        $this->base = Config::get("base.zongkong_domain", "https://ddu.jingzhe365.com");
        $this->client = new Client();
    }
    //插件远程授权
    public function addonsRemoteAuthorization(){

        $url="{$this->base}/authentication/check/addons";
        $license=request()->post('license','');
        $addons_id=request()->post('addons_id');
        $addons =Db::name('addons')->where(['addons_id'=>$addons_id])->find();
        if(!empty($addons['token'])){
            return [HTTP_SUCCESS,$addons['token']];
        }
        $body=[
            ['name' => 'addons_id','contents'=>$addons_id ],
            ['name' => 'license','contents'=>$license]
        ];
        try{

            $response=$this->request("post",$url,$body);
        }catch (GuzzleException $e){
            preg_match("{\"msg\":\"(.*)\"}",$e->getMessage(),$r);
            if(isset($r[1])){
                throw new Exception($r[1], HTTP_NOTACCEPT);
            }else{
                throw new Exception("远程校验失败", HTTP_NOTACCEPT);
            }
            
//            return [HTTP_NOTACCEPT,"插件鉴权失败".$e->getMessage()];
        }
        try{
            $token=$response['msg'];
            Db::name('addons')->where(['addons_id'=>$addons_id])->update(['token'=>$token]);

            $service= new AddonsService();
            $service->clearCache();
        }catch (\Exception $e){
            dd($e);
        }


        return [HTTP_SUCCESS,$token];
    }

    public function request($method, $url, $data = [])
    {
        $headers=[
            'domain'=>request()->host(),
            'sign'=>encode(),
            'time'=>time()
        ];
        $postVersionData = [
            'headers' => $headers,
            'multipart' => $data
        ];
        $response = $this->client->request($method, $url, $postVersionData);
        return json_decode($response->getBody()->getContents(),true);
    }

}
